function y = quad_gauss(funfcn, spans, integ_span, order, varargin)
% quad_gauss()
%     integ_span - size of integration segment

    force_plot = false;

    if (nargin == 5) % optional plot_data is present
        plot_data = varargin{1, 1};
    else
        plot_data = false;
    end

    f = fcnchk(funfcn);
    
    GaussPoints = gauss_points(order);
    pos_gauss = [GaussPoints.Position]';
    weight_gauss = [GaussPoints.Weight]';
    
    n_in_first_span = ceil((spans(1, 2) - spans(1, 1)) / integ_span) * order;
    n_long = n_in_first_span*size(spans, 1);
    pos_long = zeros(n_long, 1);
    weight_long = zeros(n_long, 1);
    N = 0;
    
    for i_span = 1:size(spans, 1)
        
        a = spans(i_span, 1);
        b = spans(i_span, 2);

        n = ceil((b - a) / integ_span);
        span = (b - a) / n;

        pos_full = zeros(n * order, 1);
        weight_full = zeros(n * order, 1);

        base = a;
        siz = span;
        pos = (base + 1/2*siz) + siz/2*pos_gauss;
        weight = 0.5 * weight_gauss;
        window_template = (1:order)';

        for i = 1:n
            pos_offset = pos + (i-1)*span;
            weight_offset = weight;

            window = window_template + (i-1)*order;

            pos_full(window) = pos_offset;
            weight_full(window) = weight_offset;
        end
        
        pos_long(N+1 : N+size(pos_full, 1), 1) = pos_full;
        weight_long(N+1 : N+size(pos_full, 1), 1) = weight_full;
        N = N + size(weight_full, 1);
        
    end
    
    pos_long = pos_long(1:N);
    weight_long = weight_long(1:N);

    val_long = f(pos_long);
    
    val_long(isnan(val_long)) = 0; % remove NaNs from integrated function
    
    if (plot_data || force_plot)
        figure; plot(pos_long, real(val_long), '.-');
        figure; plot(pos_long, imag(val_long), '.-');
        fprintf('size=%d, maxarg=%d\n', size(pos_long, 1), pos_long(size(pos_long, 1)));
    end

    y = siz * sum(val_long .* weight_long);
        
end